package com.esm.pdawms.util;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.location.Location;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static java.lang.Math.PI;

// 通用的方法

@SuppressLint("FloatMath")
public class Utils {

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private static long lastClickTime;

    // 防止快速点击按钮
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    // 完整删除指定目录
    public static void deletePath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            file.delete();
            return;
        }
        String[] nlist = file.list();
        File temp = null;
        for (int i = 0; i < nlist.length; ++i) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + nlist[i]);
            } else {
                temp = new File(path + File.separator + nlist[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            } else if (temp.isDirectory()) {
                deletePath(temp.getAbsolutePath());
            }
        }
        // delete folder
        file.delete();
    }

    // 当前是否连同网络
    public static boolean isNetConnected(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.getState() == State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public static boolean isNetPingUsable() {
        Runtime runtime = Runtime.getRuntime();
        try {
            //google
            Process process = runtime.exec("ping -c 3 www.baidu.com");
            int ret = process.waitFor();
            if (ret == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 当前是否是wifi
    public static boolean isWifiConnected(Context context) {
        return getNetworkState(context, ConnectivityManager.TYPE_WIFI) == State.CONNECTED;
    }

    // 返回当前的网络状态
    private static State getNetworkState(Context context, int networkType) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getNetworkInfo(networkType);

        return info == null ? null : info.getState();
    }

    // 存储size表示
    static public String toSDSpace(long bytes) {
        if (bytes < 100) {
            return Long.toString(bytes) + "b";
        }
        double space = bytes / 1024;
        if (space < 100) {
            int s = (int) space;
            return Integer.toString(s) + "Kb";
        }
        space = space / 1024;
        if (space < 100) {
            int s = (int) space;
            return Integer.toString(s) + "MB";
        } else {
            space = space / 1024;
            DecimalFormat df = new DecimalFormat();
            df.setMaximumFractionDigits(2);
            df.setMinimumFractionDigits(2);
            return df.format(space) + "GB";
        }
    }

    // 指定目录的剩余空间
    @SuppressWarnings("deprecation")
    static public long getFreeSpace(String path) {
        StatFs sf = new StatFs(path);
        long blockSize = sf.getBlockSize();
        long availCount = sf.getAvailableBlocks();
        long freeSpace = availCount * blockSize;
        return freeSpace;
    }

    // 指定目录的剩余空间－string信息
    static public String getSDSpaceInfo(String path) {
        String name = new File(path).getName();
        if (name == null || name.length() == 0) {
            return "";
        }
        long free = getFreeSpace(path);
        long total = getTotalSpace(path);
        String info = name + "\n可用空间" + toSDSpace(free) + "\n总容量:"
                + toSDSpace(total);
        return info;
    }

    // sd卡的剩余空间
    @SuppressWarnings("deprecation")
    public static long getSDFreeSpace() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            long blockSize = sf.getBlockSize();
            long availCount = sf.getAvailableBlocks();
            long freeSpace = availCount * blockSize;
            return freeSpace;
        }
        return 0;
    }

    // 指定目录的空间
    @SuppressWarnings("deprecation")
    static public long getTotalSpace(String path) {
        StatFs sf = new StatFs(path);
        long blockSize = sf.getBlockSize();
        long blockCount = sf.getBlockCount();
        // long availCount = sf.getAvailableBlocks();
        long totalSpace = blockCount * blockSize;
        return totalSpace;
    }

    // scan all sd that maybe sd card under /storage/ dir
    // 找到所有的SDcard
    static public ArrayList<String> scanAllMaybeSD(boolean isForpic) {
        ArrayList<String> allSD = new ArrayList<String>();
        File fileold = new File("/storage/");
        try {
            File[] files = fileold.listFiles();
            if (files.length > 0) {
                for (int j = 0; j < files.length; j++) {
                    String fName = files[j].getName();
                    if (fName.contains("Sd") || fName.contains("sd")) {
                        if (files[j].isDirectory()) {
                            if (isForpic
                                    || getTotalSpace(files[j].getPath()) > 1024 * 1024 * 1000) { // 1G
                                allSD.add(files[j].getPath());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }

        if (allSD.size() < 1) {
            fileold = new File("/mnt/");
            try {
                File[] files = fileold.listFiles();
                if (files.length > 0) {
                    for (int j = 0; j < files.length; j++) {
                        String fName = files[j].getName();
                        if (fName.contains("Sd") || fName.contains("sd")) {
                            if (files[j].isDirectory()) {
                                if (isForpic
                                        || getTotalSpace(files[j].getPath()) > 1024 * 1024 * 500) { // 500mb
                                    allSD.add(files[j].getPath());
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {

            }
        }

        if (allSD.size() < 1) {
            fileold = new File("/");
            try {
                File[] files = fileold.listFiles();
                if (files.length > 0) {
                    for (int j = 0; j < files.length; j++) {
                        String fName = files[j].getName();
                        if (fName.contains("Sd") || fName.contains("sd")) {
                            if (files[j].isDirectory()) {
                                if (isForpic
                                        || getTotalSpace(files[j].getPath()) > 1024 * 1024 * 1000) { // 1G
                                    allSD.add(files[j].getPath());
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {

            }
        }

        return allSD;
    }

    // 获取设备信息
    static public String getDeviceInfo() {
        String model = Build.MODEL;
        int sdkVer = Build.VERSION.SDK_INT;
        String relVer = Build.VERSION.RELEASE;
        String brand = Build.BRAND;
        String manu = Build.MANUFACTURER;
        // String user = android.os.Build.USER;
        JSONObject json = new JSONObject();
        try {
            json.put("model", model);
            json.put("sdk", sdkVer);
            json.put("ver", relVer);
            json.put("brand", brand);
            json.put("manu", manu);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    // sdcard是否被禁止写文件
    public static boolean isSDForbidden() {
        if (Build.VERSION.SDK_INT >= 19) {
            return true;
        }
        return false;
    }

    // 获取默认SDcard的目录
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        return sdDir.toString();
    }

    public static String getDBPath() {
        String sdCardPath = getSDPath();
        if (TextUtils.isEmpty(sdCardPath)) {
            return "";
        } else {
            return sdCardPath + File.separator + "BHCMapper"
                    + File.separator + "sqlite";
        }
    }


    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    @SuppressWarnings("unused")
    public static boolean copyFile(String oldPath, String newPath) {
        boolean isok = true;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    // System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                fs.flush();
                fs.close();
                inStream.close();
            } else {
                isok = false;
            }
        } catch (Exception e) {
            // System.out.println("复制单个文件操作出错");
            // e.printStackTrace();
            isok = false;
        }
        return isok;

    }

    // 输入框判断
    // maxLength is byte length, 1 hanzi = 3 bytes
    public static InputFilter getInputFilter(final Context context,
                                             final int maxLength) {
        return new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                int destLen = dest.toString().getBytes().length;
                int sourceLen = source.toString().getBytes().length;
                // 如果超过100个字
                if (destLen + sourceLen > maxLength) {
                    Toast.makeText(context, "输入已超过最大长度", Toast.LENGTH_SHORT)
                            .show();
                    return "";
                }
                // 如果按回退
                if (source.length() < 1 && (dend - dstart >= 1)) {
                    return dest.subSequence(dstart, dend - 1);
                }
                // 其他情况直接返回输入的内
                return source;
            }
        };
    }

    // 命令
    public static void chmod(String permission, String path) {
        try {
            String command = "chmod " + permission + " " + path;
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 将assets的文件copy出来
    public static boolean retrieveApkFromAssets(Context context,
                                                String fileName, String path) {
        if (context == null) {
            return false;
        }
        boolean bRet = false;

        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);

            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }

            fos.close();
            is.close();

            bRet = true;

        } catch (IOException e) {
            e.printStackTrace();
        }

        File f1 = new File(path);
        if (f1 != null && f1.exists()) {
            Uri localUri = Uri.fromFile(f1);
            Intent localIntent = new Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
            context.sendBroadcast(localIntent);
        }

        return bRet;
    }


    // IMEI相关
    // IMEI是否有效
    private static boolean isValidImei(String imei) {
        if (imei == null) {
            return false;
        }
        if (imei.length() == 0) {
            return false;
        }
        boolean valid = false;
        for (int i = 0; i < imei.length(); ++i) {
            if (imei.charAt(i) != '0') {
                valid = true;
                break;
            }
        }
        return valid;
    }

    //使用ANDROID_ID作为IMEI
    public static String getIMEI(Context context) {
        if (context == null) {
            return "";
        }
        String deviceId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return deviceId;
    }

    // 图片操作相关
    public static Bitmap getResizedBitmap(String path, byte[] data,
                                          Context context, Uri uri, int target, boolean width) {
        Options options = null;

        if (target > 0) {

            Options info = new Options();
            // 这里设置true的时候，decode时候Bitmap返回的为空，
            // 将图片宽高读取放在Options里.
            info.inJustDecodeBounds = false;

            decode(path, data, context, uri, info);

            int dim = info.outWidth;
            if (!width)
                dim = Math.max(dim, info.outHeight);
            int ssize = sampleSize(dim, target);

            options = new Options();
            options.inSampleSize = ssize;

        }

        Bitmap bm = null;
        try {
            bm = decode(path, data, context, uri, options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;

    }

    public static Bitmap decode(String path, byte[] data, Context context,
                                Uri uri, Options options) {
        Bitmap result = null;
        if (path != null) {
            result = BitmapFactory.decodeFile(path, options);
        } else if (data != null) {
            result = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
        } else if (uri != null) {
            ContentResolver cr = context.getContentResolver();
            InputStream inputStream = null;
            try {
                inputStream = cr.openInputStream(uri);
                result = BitmapFactory.decodeStream(inputStream, null, options);
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static int sampleSize(int width, int target) {
        int result = 1;
        for (int i = 0; i < 10; i++) {
            if (width < target * 2) {
                break;
            }
            width = width / 2;
            result = result * 2;
        }
        return result;
    }

    // Bitmap存成png
    public static void saveBitmap(String picName, Bitmap bm) {
        File f = new File(picName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // Bitmap存成jpg
    public static void saveBitmap2jpg(String jpgpath, Bitmap bm) {
        if (bm == null) {
            return;
        }
        File f = new File(jpgpath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //    https://www.cnblogs.com/android-blogs/p/5586480.html
    public static Bitmap getFitSampleBitmap(String file_path, int width, int height) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file_path, options);
        options.inSampleSize = getFitInSampleSize(width, height, options);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(file_path, options);
    }

    public static int getFitInSampleSize(int reqWidth, int reqHeight, Options options) {
        int inSampleSize = 1;
        if (options.outWidth > reqWidth || options.outHeight > reqHeight) {
            int widthRatio = Math.round((float) options.outWidth / (float) reqWidth);
            int heightRatio = Math.round((float) options.outHeight / (float) reqHeight);
            inSampleSize = Math.min(widthRatio, heightRatio);
        }
        return inSampleSize;
    }


    // 加载图片文件->Bitmap
    public static Bitmap loadBitmap(String filepath) {
        if (filepath == null || filepath.length() == 0) {
            return null;
        }
        Bitmap bitmap = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filepath);
            bitmap = BitmapFactory.decodeStream(fis);
            // Drawable drawable = new BitmapDrawable(bitmap);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }

    // 缩放Bitmap到指定的大小
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        if (bitmap == null) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidht = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidht, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newbmp;
    }

    // 旋转Bitmap
    public static Bitmap rotateBitmap(Bitmap bitmap, int degree) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.setRotate(degree);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newbmp;
    }

    // 获取jpg的方向
    public static int getExifOrientation(String filepath) {
        int degree = 0;
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filepath);
        } catch (IOException ex) {

        }
        if (exif != null) {
            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, -1);
            if (orientation != -1) {
                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }

            }
        }
        return degree;
    }

    /*
     * 目前Android SDK定义的Tag有: TAG_DATETIME 时间日期 TAG_FLASH 闪光灯 TAG_GPS_LATITUDE 纬度
     * TAG_GPS_LATITUDE_REF 纬度参考 TAG_GPS_LONGITUDE 经度 TAG_GPS_LONGITUDE_REF 经度参考
     * TAG_IMAGE_LENGTH 图片长 TAG_IMAGE_WIDTH 图片宽 TAG_MAKE 设备制造商 TAG_MODEL 设备型号
     * TAG_ORIENTATION 方向 TAG_WHITE_BALANCE 白平衡
     */
    // 获取照片日期String
    @SuppressLint("SimpleDateFormat")
    public static String getExifDatetime(String filepath) {
        String strDatetime = "";
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filepath);
        } catch (IOException ex) {
            return strDatetime;
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        if (exif != null) {
            // 2014:12:11 10:32:21
            strDatetime = exif.getAttribute(ExifInterface.TAG_DATETIME);
        }

        if (strDatetime == null) {
            File f = new File(filepath);
            long time = f.lastModified();
            Date curDate = new Date(time);
            strDatetime = formatter.format(curDate);
        }

        return strDatetime;
    }


    public static String decimalToDMS(double coord) {
        String output, degrees, minutes, seconds;

        // gets the modulus the coordinate divided by one (MOD1).
        // in other words gets all the numbers after the decimal point.
        // e.g. mod := -79.982195 % 1 == 0.982195
        //
        // next get the integer part of the coord. On other words the whole
        // number part.
        // e.g. intPart := -79

        double mod = coord % 1;
        int intPart = (int) coord;

        // set degrees to the value of intPart
        // e.g. degrees := "-79"

        degrees = String.valueOf(intPart);

        // next times the MOD1 of degrees by 60 so we can find the integer part
        // for minutes.
        // get the MOD1 of the new coord to find the numbers after the decimal
        // point.
        // e.g. coord := 0.982195 * 60 == 58.9317
        // mod := 58.9317 % 1 == 0.9317
        //
        // next get the value of the integer part of the coord.
        // e.g. intPart := 58

        coord = mod * 60;
        mod = coord % 1;
        intPart = (int) coord;
        if (intPart < 0) {
            // Convert number to positive if it's negative.
            intPart *= -1;
        }

        // set minutes to the value of intPart.
        // e.g. minutes = "58"
        minutes = String.valueOf(intPart);

        // do the same again for minutes
        // e.g. coord := 0.9317 * 60 == 55.902
        // e.g. intPart := 55
        coord = mod * 60;
        intPart = (int) coord;
        if (intPart < 0) {
            // Convert number to positive if it's negative.
            intPart *= -1;
        }

        // set seconds to the value of intPart.
        // e.g. seconds = "55"
        seconds = String.valueOf(intPart);

        // I used this format for android but you can change it
        // to return in whatever format you like
        // e.g. output = "-79/1,58/1,56/1"
        output = degrees + "/1," + minutes + "/1," + seconds + "/1";

        // Standard output of D°M′S″
        // output = degrees + "°" + minutes + "'" + seconds + "\"";

        return output;
    }

    public static void writeLatLonIntoJpeg(String picPath, double dLat, double dLon) {
        File file = new File(picPath);
        if (file.exists()) {
            try {
                ExifInterface exif = new ExifInterface(picPath);
                String tagLat = exif
                        .getAttribute(ExifInterface.TAG_GPS_LATITUDE);
                String tagLon = exif
                        .getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
                if (tagLat == null && tagLon == null) // 无经纬度信息
                {
                    exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE,
                            decimalToDMS(dLat));
                    exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF,
                            dLat > 0 ? "N" : "S"); // 区分南北半球
                    exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE,
                            decimalToDMS(dLon));
                    exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF,
                            dLon > 0 ? "E" : "W"); // 区分东经西经

                    exif.saveAttributes();
                }
            } catch (Exception e) {

            }
        }
    }

    // 获取照片日期long
    @SuppressLint("SimpleDateFormat")
    public static long getExifDatelongtime(String filepath) {
        String strDatetime = "";
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filepath);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        if (exif != null) {
            // 2014:12:11 10:32:21
            strDatetime = exif.getAttribute(ExifInterface.TAG_DATETIME);
        }

        long time = 0;
        if (strDatetime != null) {
            try {
                Date a = formatter.parse(strDatetime);
                time = a.getTime();
                return time;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        File f = new File(filepath);
        time = f.lastModified();

        return time;
    }

    // 经纬度格式转化
    public static float convertRationalLatLonToFloat(String rationalString,
                                                     String ref) {
        try {
            String[] parts = rationalString.split(",");

            String[] pair;
            pair = parts[0].split("/");
            int degrees = (int) (Float.parseFloat(pair[0].trim()) / Float
                    .parseFloat(pair[1].trim()));

            pair = parts[1].split("/");
            int minutes = (int) ((Float.parseFloat(pair[0].trim()) / Float
                    .parseFloat(pair[1].trim())));

            pair = parts[2].split("/");
            float seconds = Float.parseFloat(pair[0].trim())
                    / Float.parseFloat(pair[1].trim());

            float result = degrees + (minutes / 60F) + (seconds / (60F * 60F));
            if ((ref.equals("S") || ref.equals("W"))) {
                return -result;
            }
            return result;
        } catch (RuntimeException ex) {
            // if for whatever reason we can't parse the lat long then return
            // null
            return 0f;
        }
    }

    // 求两点间距离：
    public static double spacing(MotionEvent event) {
        double x = event.getX(0) - event.getX(1);
        double y = event.getY(0) - event.getY(1);
        return Math.sqrt(x * x + y * y);
    }

    // 求两点间中点：
    public static void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    // TextView自动换行文字排版参差不齐的原因
    // 半角转为全角
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    // 替换、过滤特殊字符
    // 在标点符号后加一个空格。
    public static String StringFilter(String str) throws PatternSyntaxException {
        str = str.replaceAll("【", "[").replaceAll("】", "]")
                .replaceAll("！", "!");// 替换中文标号
        str = str.replaceAll(",", ", ").replaceAll("。", "。 ")
                .replaceAll("!", "! ");
        String regEx = "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    //gps转度分秒
    public static String gpsInfoConvert(double gpsInfo) {
        gpsInfo = Math.abs(gpsInfo);
        String dms = Location.convert(gpsInfo, Location.FORMAT_SECONDS);
        String[] splits = dms.split(":");
        String[] secnds = (splits[2]).split("\\.");
//        String seconds;
//        if (secnds.length == 0) {
//            seconds = splits[2];
//        } else {
//            seconds = secnds[0];
//        }
//        return splits[0] + "°" + splits[1] + "′" + seconds + "″";
        return splits[0] + "°" + splits[1] + "′" + splits[2] + "″";
    }

    //度分秒转gps
    public static double convertToDegree(String stringDMS) {
        Float result = null;
        String[] DMS = stringDMS.split(",", 3);

        String[] stringD = DMS[0].split("/", 2);
        Double D0 = new Double(stringD[0]);
        Double D1 = new Double(stringD[1]);
        Double FloatD = D0 / D1;

        String[] stringM = DMS[1].split("/", 2);
        Double M0 = new Double(stringM[0]);
        Double M1 = new Double(stringM[1]);
        Double FloatM = M0 / M1;

        String[] stringS = DMS[2].split("/", 2);
        Double S0 = new Double(stringS[0]);
        Double S1 = new Double(stringS[1]);
        Double FloatS = S0 / S1;

        result = new Float(FloatD + (FloatM / 60) + (FloatS / 3600));

        return (double) result;
    }

    static public Bitmap toRoundBitmap(Bitmap bitmap) {
        //圆形图片宽高
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        //正方形的边长
        int r = 0;
        //取最短边做边长
        if (width > height) {
            r = height;
        } else {
            r = width;
        }
        //构建一个bitmap
        Bitmap backgroundBmp = Bitmap.createBitmap(width,
                height, Bitmap.Config.ARGB_8888);
        //new一个Canvas，在backgroundBmp上画图
        Canvas canvas = new Canvas(backgroundBmp);
        Paint paint = new Paint();
        //设置边缘光滑，去掉锯齿
        paint.setAntiAlias(true);
        //宽高相等，即正方形
        RectF rect = new RectF(0, 0, r, r);
        //通过制定的rect画一个圆角矩形，当圆角X轴方向的半径等于Y轴方向的半径时，
        //且都等于r/2时，画出来的圆角矩形就是圆形
        canvas.drawRoundRect(rect, r / 2, r / 2, paint);
        //设置当两个图形相交时的模式，SRC_IN为取SRC图形相交的部分，多余的将被去掉
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //canvas将bitmap画在backgroundBmp上
        canvas.drawBitmap(bitmap, null, rect, paint);
        //返回已经绘画好的backgroundBmp
        return backgroundBmp;
    }

    // 时间相关
    public static long getDateTime(String dateTimeString, SimpleDateFormat sFormatter) {
        if (dateTimeString == null || sFormatter == null)
            return -1;

        // sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        ParsePosition pos = new ParsePosition(0);
        try {
            Date datetime = sFormatter.parse(dateTimeString, pos);
            if (datetime == null)
                return -1;
            return datetime.getTime();
        } catch (IllegalArgumentException ex) {
            return -1;
        }
    }

    @SuppressLint("SimpleDateFormat")
    public static String DateConverToString(Date date, SimpleDateFormat df) {
        if (date == null || df == null) {
            return "";
        }
        return df.format(date);
    }

    public static int stringToInt(String str) {
        String tmpStr = "";
        if (str.length() > 0) {
            for (int i = 0; i < str.length(); i++) {
                String tmp = "" + str.charAt(i);
                if ((tmp).matches("[0-9.]")) {
                    tmpStr += tmp;
                }
            }
        }

        if (tmpStr.length() < 1) {
            return -1;
        }
        Integer integer;
        integer = Integer.parseInt(tmpStr);
        return integer.intValue();
    }

    public static double transformlat(double lng, double lat) {
        double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    public static double transformlng(double lng, double lat) {
        double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }


    /**
     * 判断是否在国内，不在国内则不做偏移
     *
     * @param lng
     * @param lat
     * @returns {boolean}
     */
    public static boolean out_of_china(double lng, double lat) {
        // 纬度3.86~53.55,经度73.66~135.05
        return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
    }

    public static String getDistanceStr(int distance) {
        DecimalFormat DF = new DecimalFormat("0.0");
        String strDistance, strUnit;
        if (distance >= 10000) {
            strDistance = new DecimalFormat("0").format(distance / 1000);
            strUnit = "km";
        } else if (distance >= 1000) {
            strDistance = new DecimalFormat("0.0").format(distance / 1000.0);
            strUnit = "km";
        } else {
            strDistance = new DecimalFormat("0").format(distance);
            strUnit = "m";
        }

        return strDistance + strUnit;
    }

    //判断点在多边形内
    public static boolean pointInPolygon(Point pt, ArrayList<Point> regions) {
        if (pt == null || regions == null || regions.size() < 3) {
            return false;
        }
        boolean oddNodes = false;
        int size = regions.size();
        int j = size - 1;
        for (int i = 0; i < size; i++) {
            Point A = regions.get(i);
            Point B = regions.get(j);
            if ((A.y < pt.y && B.y >= pt.y || B.y < pt.y && A.y >= pt.y)
                    && (A.x <= pt.x || B.x <= pt.x)) {
                if (A.x + (pt.y - A.y) / (B.y - A.y) * (B.x - A.x) < pt.x) {
                    oddNodes = !oddNodes;
                }
            }
            j = i;
        }
        return oddNodes;
    }

    /**
     * <p> 判断线段是否在矩形内
     * <p>
     * 先看线段所在直线是否与矩形相交，
     * 如果不相交则返回false，
     * 如果相交，
     * 则看线段的两个点是否在矩形的同一边（即两点的x(y)坐标都比矩形的小x(y)坐标小，或者大）,
     * 若在同一边则返回false，
     * 否则就是相交的情况。
     * </p>
     * <p>
     * //     * @param linePointX1 线段起始点x坐标
     * //     * @param linePointY1 线段起始点y坐标
     * //     * @param linePointX2 线段结束点x坐标
     * //     * @param linePointY2 线段结束点y坐标
     * //     * @param rectangleLeftTopX 矩形左上点x坐标
     * //     * @param rectangleLeftTopY 矩形左上点y坐标
     * //     * @param rectangleRightBottomX 矩形右下点x坐标
     * //     * @param rectangleRightBottomY 矩形右下点y坐标
     *
     * @return 是否相交
     */
    public static boolean isLineIntersectRectangle(double[] regions, double[] line) {
//regions--_maxLon, _maxLat, _minLon, _minLat
//line --- lon0, lat0, lon1, lat1,
        if (regions == null || regions.length != 4) {
            return false;
        }
        if (line == null || line.length != 4) {
            return false;
        }
        int LX = 10000;//浮点经纬度转整型经纬度
        int linePointX1 = (int) (LX * line[0]);
        int linePointY1 = (int) (LX * line[1]);
        int linePointX2 = (int) (LX * line[2]);
        int linePointY2 = (int) (LX * line[3]);
        int rectangleLeftTopX = (int) (LX * regions[2]);
        int rectangleLeftTopY = (int) (LX * regions[3]);
        int rectangleRightBottomX = (int) (LX * regions[0]);
        int rectangleRightBottomY = (int) (LX * regions[1]);
        return isLineIntersectRectangle(linePointX1, linePointY1, linePointX2, linePointY2, rectangleLeftTopX, rectangleLeftTopY, rectangleRightBottomX, rectangleRightBottomY);
    }

    public static boolean isLineIntersectRectangle(int linePointX1, int linePointY1, int linePointX2, int linePointY2, int rectangleLeftTopX, int rectangleLeftTopY, int rectangleRightBottomX, int rectangleRightBottomY) {

        int lineHeight = linePointY1 - linePointY2;
        int lineWidth = linePointX2 - linePointX1;
        // 计算叉乘
        int c = linePointX1 * linePointY2 - linePointX2 * linePointY1;

        if ((lineHeight * rectangleLeftTopX + lineWidth * rectangleLeftTopY + c >= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleRightBottomY + c <= 0)
                || (lineHeight * rectangleLeftTopX + lineWidth * rectangleLeftTopY + c <= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleRightBottomY + c >= 0)
                || (lineHeight * rectangleLeftTopX + lineWidth * rectangleRightBottomY + c >= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleLeftTopY + c <= 0)
                || (lineHeight * rectangleLeftTopX + lineWidth * rectangleRightBottomY + c <= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleLeftTopY + c >= 0)) {
            if (rectangleLeftTopX > rectangleRightBottomX) {
                int temp = rectangleLeftTopX;
                rectangleLeftTopX = rectangleRightBottomX;
                rectangleRightBottomX = temp;
            }
            if (rectangleLeftTopY < rectangleRightBottomY) {
                int temp = rectangleLeftTopY;
                rectangleLeftTopY = rectangleRightBottomY;
                rectangleRightBottomY = temp;
            }
            if ((linePointX1 < rectangleLeftTopX && linePointX2 < rectangleLeftTopX)
                    || (linePointX1 > rectangleRightBottomX && linePointX2 > rectangleRightBottomX)
                    || (linePointY1 > rectangleLeftTopY && linePointY2 > rectangleLeftTopY)
                    || (linePointY1 < rectangleRightBottomY && linePointY2 < rectangleRightBottomY)) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    //设置语言
    /*
    /values    --缺省可以作为英语
    /values-zh  -- 中国
    /values-zh-rCN  -- android 设置里的语言选择
    /values-zh-rTW -- 中国台湾地图(r表示地区)
    */
    public static void setLanguage(Context context, Locale locale) {
        Configuration config = context.getResources().getConfiguration();//获取系统的配置
        config.locale = Locale.TRADITIONAL_CHINESE;//将语言更改为繁体中文
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());//更新配置
    }

    public static String getTimeDF(int secondtime) {
        if (secondtime < 0) {
            secondtime = 0;
        }
        DecimalFormat DF = new DecimalFormat("00");
        int hour = secondtime / 3600;
        int min = (secondtime % 3600) / 60;
        int second = secondtime % 60;
        String strTime = DF.format(hour) + ":" + DF.format(min) + ":" + DF.format(second);
        return strTime;
    }


    //删除文件夹和文件夹里面的文件
    public static void deleteDir(final String pPath) {
        File dir = new File(pPath);
        deleteDirWihtFile(dir);
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    // 求矩形截取线段，新线段AB的点， 返回是false 就可以不用画
    //line(0,1,2,3);
    public static boolean revisePt(int[] line, int w, int h) {
        if (line == null || line.length != 4) {
            return false;
        }
        int x0 = line[0];
        int y0 = line[1];
        int x1 = line[2];
        int y1 = line[3];

        if (Math.abs(line[0] - line[2]) + Math.abs(line[1] - line[3]) <= 1) {
            return false;
        }

        if (x0 == x1) {
            //k == 0 斜率为0
            if (line[1] < 0) {
                line[1] = 0;
            }
            if (line[1] > h) {
                line[1] = h;
            }
            if (line[3] < 0) {
                line[3] = 0;
            }
            if (line[3] > h) {
                line[3] = h;
            }
            return true;
        }

        boolean isAIn = false;
        boolean isBIn = false;

        //两个点都在屏幕内
        if (x0 >= 0 && x0 <= w && y0 >= 0 && y0 <= h) {
            isAIn = true;
        }

        if (x1 >= 0 && x1 <= w && y1 >= 0 && y1 <= h) {
            isBIn = true;
        }

        if (isBIn && isAIn) {
            return true;
        }

        if (isAIn) {
            return AinBout(line, w, h);
        } else if (isBIn) {
            line[0] = x1;
            line[1] = y1;
            line[2] = x0;
            line[3] = y0;

            if (AinBout(line, w, h)) {
                int x = line[0];
                int y = line[1];
                line[0] = line[2];
                line[1] = line[3];
                line[2] = x;
                line[3] = y;
                return true;
            }
            return false;
        } else {
            //都在屏幕外,求直线和四边的交点
            return AoutBout(line, w, h);
        }

    }

    //两点直线方程 (y-y0)/(y0-y1)=(x-x0)/(x0-x1)
    // y = k*(x-x0)+y0
    // x = (y-y0)/k+x0;
    //A点(0,1)在屏幕内,B点（2，3）在屏幕外
    public static boolean AinBout(int[] line, int w, int h) {
        if (line == null || line.length != 4) {
            return false;
        }

        int x0 = line[0];
        int y0 = line[1];
        int x1 = line[2];
        int y1 = line[3];
        if (x0 == x1) {
            return true;
        }
        double k = (double) (y0 - y1) / (x0 - x1);

        int y = 0;
        int x = 0;

        if (y1 < 0) {
            //1. 和矩形上边的交点
            y = 0;
            x = (int) ((y - y0) / k + x0);

            //如果交点在上边延长线较远处，则求和侧边的交点
            if (x - w > 1000) {
                //右延长线
                x = w;
                y = (int) (k * (x - x0) + y0);
            } else if (w - x > 1000) {
                //左延长线
                x = 0;
                y = (int) (k * (x - x0) + y0);
            }
        } else if (y1 > h) {
            //2. 和矩形下边的交点
            y = h;
            x = (int) ((y - y0) / k + x0);

            //如果交点在上边延长线较远处，则求和侧边的交点
            if (x - w > 1000) {
                //右延长线
                x = w;
                y = (int) (k * (x - x0) + y0);
            } else if (w - x > 1000) {
                //左延长线
                x = 0;
                y = (int) (k * (x - x0) + y0);
            }
        } else {
            //B点在矩形两边
            if (x1 > w) {
                //矩形右侧
                x = w;
                y = (int) (k * (x - x0) + y0);
            } else if (x1 < 0) {
                //矩形左侧
                x = 0;
                y = (int) (k * (x - x0) + y0);
            }
        }

        line[2] = x;
        line[3] = y;

        return true;
    }

    public static boolean AoutBout(int[] line, int w, int h) {
        if (line == null || line.length != 4) {
            return false;
        }

        int x0 = line[0];
        int y0 = line[1];
        int x1 = line[2];
        int y1 = line[3];
        if (x0 == x1) {
            return true;
        }
        double k = (double) (y0 - y1) / (x0 - x1);

        int xMin = Math.min(x0, x1);
        int yMin = Math.min(y0, y1);
        int xMax = Math.max(x0, x1);
        int yMax = Math.max(y0, y1);

        //AB点都在矩形外，AB直线和矩形没有交点，或只有2交点
        //要就没有，有一个就必有第二个

        //1. 和矩形上边的交点
        int yA = 0;
        int xA = (int) ((yA - y0) / k + x0);

        //2. 和矩形右边的交点
        int xB = w;
        int yB = (int) (k * (xB - x0) + y0);

        //3. 和矩形下边的交点
        int yC = h;
        int xC = (int) ((yC - y0) / k + x0);

        //4. 和矩形左边的交点
        int xD = 0;
        int yD = (int) (k * (xD - x0) + y0);

        int valid = 0;
        //交点在线段的矩形范围内
        if (xA >= 0 && xA <= w && xA >= xMin && xA <= xMax && yA >= yMin && yA <= yMax) {
            x0 = xA;
            y0 = yA;
            valid++;
        }

        if (xC >= 0 && xC <= w && xC >= xMin && xC <= xMax && yC >= yMin && yC <= yMax) {
            if (valid == 0) {
                x0 = xC;
                y0 = yC;
            } else {
                x1 = xC;
                y1 = yC;
            }
            valid++;
        }

        if (yB >= 0 && yB <= h && xB >= xMin && xB <= xMax && yB >= yMin && yB <= yMax) {
            if (valid == 0) {
                x0 = xB;
                y0 = yB;
            } else {
                x1 = xB;
                y1 = yB;
            }
            valid++;
        }

        if (yD >= 0 && yD <= h && xD >= xMin && xD <= xMax && yD >= yMin && yD <= yMax) {
            if (valid == 0) {
                x0 = xD;
                y0 = yD;
            } else {
                x1 = xD;
                y1 = yD;
            }
            valid++;
        }

        if (valid == 2) {
            line[0] = x0;
            line[1] = y0;
            line[2] = x1;
            line[3] = y1;
            return true;
        }

        return false;
    }

    public static Collection<? extends File> scan(File f) {
        List<File> ret = new ArrayList<>();
        File[] files = f.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (pathname.getName().toLowerCase().endsWith(".gpx"))
                    return true;
                return false;
            }
        });
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                ret.add(files[i]);
            }
        }
        return ret;
    }

    // 点到直线的最短距离的判断 点（x0,y0） 到由两点组成的线段（x1,y1） ,( x2,y2 )
    public static double pointToLine(int x1, int y1, int x2, int y2, int x0,
                                     int y0) {
        double space = 0;
        double a, b, c;
        a = lineSpace(x1, y1, x2, y2);// 线段的长度
        b = lineSpace(x1, y1, x0, y0);// (x1,y1)到点的距离
        c = lineSpace(x2, y2, x0, y0);// (x2,y2)到点的距离
        if (c <= 0.000001 || b <= 0.000001) {
            space = 0;
            return space;
        }
        if (a <= 0.000001) {
            space = b;
            return space;
        }
        if (c * c >= a * a + b * b) {
            space = b;
            return space;
        }
        if (b * b >= a * a + c * c) {
            space = c;
            return space;
        }
        double p = (a + b + c) / 2;// 半周长
        double s = Math.sqrt(p * (p - a) * (p - b) * (p - c));// 海伦公式求面积
        space = 2 * s / a;// 返回点到线的距离（利用三角形面积公式求高）
        return space;
    }

    // 计算两点之间的距离
    public static double lineSpace(int x1, int y1, int x2, int y2) {
        double lineLength = 0;
        lineLength = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
                * (y1 - y2));
        return lineLength;
    }

    //    主板 Build.BOARD :sdm660
//    系统启动程序版本号：Build.BOOTLOADER: unknown
//    系统定制商： Build.BRAND :xiaomi
//    cpu指令集：Build.CPU_ABI :arm64-v8a
//    cpu指令集2 Build.CPU_ABI2:
//    设置参数： Build.DEVICE:lavender
//    显示屏参数：Build.DISPLAY:PKQ1.180904.001
//    无线电固件版本：Build.getRadioVersion():MPSS.AT.3.1-00777-SDM660_GEN_PACK-1.209285.1.210383.1
//    硬件识别码： Build.FINGERPRINT:xiaomi/lavender/lavender:9/PKQ1.180904.001/V11.0.4.0.PFGCNXM:user/release-keys
//    硬件名称： Build.HARDWARE:qcom
//    HOST: Build.HOST:c4-miui-ota-bd05.bj
//    Build.ID);Build.ID:PKQ1.180904.001
//    硬件制造商： Build.MANUFACTURER:Xiaomi
//    版本： Build.MODEL:Redmi Note 7
//    硬件序列号： Build.SERIAL:unknown
//    手机制造商：Build.PRODUCT: lavender
//    描述Build的标签： Build.TAGS:release-keys
//    TIME: Build.TIME :1573372247000
//    builder类型 Build.TYPE:user
//    USER: Build.USER:builder
    public static String getDeviceInfo2() {
        StringBuffer sb = new StringBuffer();
        sb.append("主板 Build.BOARD :" + Build.BOARD);
        sb.append(
                "\n系统启动程序版本号：Build.BOOTLOADER: " + Build.BOOTLOADER);
        sb.append(
                "\n系统定制商： Build.BRAND :" + Build.BRAND);
        sb.append(
                "\ncpu指令集：Build.CPU_ABI :" + Build.CPU_ABI);
        sb.append(
                "\ncpu指令集2 Build.CPU_ABI2: " + Build.CPU_ABI2);
        sb.append(
                "\n设置参数： Build.DEVICE:" + Build.DEVICE);
        sb.append(
                "\n显示屏参数：Build.DISPLAY:" + Build.DISPLAY);
        sb.append("\n无线电固件版本：Build.getRadioVersion():" + Build.getRadioVersion());
        sb.append("\n硬件识别码： Build.FINGERPRINT:" + Build.FINGERPRINT);
        sb.append("\n硬件名称： Build.HARDWARE:" + Build.HARDWARE);
        sb.append("\nHOST: Build.HOST:" + Build.HOST);
        sb.append("\nBuild.ID);Build.ID:" + Build.ID);
        sb.append("\n硬件制造商： Build.MANUFACTURER:" + Build.MANUFACTURER);
        sb.append("\n版本： Build.MODEL:" + Build.MODEL);
        sb.append("\n硬件序列号： Build.SERIAL:" + Build.SERIAL);
        sb.append("\n手机制造商：Build.PRODUCT: " + Build.PRODUCT);
        sb.append("\n 描述Build的标签： Build.TAGS:" + Build.TAGS);
        sb.append("\nTIME: Build.TIME :" + Build.TIME);
        sb.append("\nbuilder类型 Build.TYPE:" + Build.TYPE);
        sb.append("\nUSER: Build.USER:" + Build.USER);
        return sb.toString();
    }


    //demo SharedPreferences
//    private String getDeviceId2() {
//        String info = Utils.getDeviceInfo2();
//
//        SharedPreferences sp = context.getSharedPreferences("SERIAL_FEIGE", Context.MODE_PRIVATE);
//
//        String code = Build.SERIAL;
//        if (code.isEmpty() || code.compareToIgnoreCase("unknown") == 0) {
//            code = sp.getString("SERIAL", "");
//
//            if (code.length() < 1) {
//                //自动生成IMEI
//                code = MD5Util.MD5(System.currentTimeMillis() + Build.PRODUCT);
//            }
//        }
//        int max = 11;
//
//        int size = code.length();
//        if (size < max) {
//            for (int i = size; i < max; i++) {
//                code += "0";
//            }
//        } else if (size > max) {
//            code = code.substring(size - max);
//        }
//
//        SharedPreferences.Editor editor = sp.edit();
//        editor.putString("SERIAL", code);
//        editor.commit();
//
//        return code.toLowerCase();
//    }

    private static FileOutputStream mFout = null;

    public static void log(String message) {
        String RUNDIR = Environment.getExternalStorageDirectory() + "/Mego/";

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date();
        String strDate = formatter.format(curDate);
        message += "[" + strDate + "]\n";

        if (mFout == null) {
            try {
                File file = new File(RUNDIR + "/log.txt");
                if (file.exists())
                    file.delete();
                file.createNewFile();
                mFout = new FileOutputStream(RUNDIR + "/log.txt");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            byte[] bytes = message.getBytes();
            mFout.write(bytes);
            mFout.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 包括小数点
    public static String getNumberD(String s) {
        if (s.isEmpty()) {
            return "";
        }

        String numberString = "";
        String single = "";
        boolean haveP = false;//只能有一个小数点
        for (int i = 0; i < s.length(); i++) {
            single = s.substring(i, i + 1);
            if ((single.compareToIgnoreCase("-") == 0 && i == 0)) {
                numberString += single;
            }
            if (!haveP && single.compareToIgnoreCase(".") == 0) {
                numberString += single;
                haveP = true;
            }
        }

        return numberString;
    }

    //产生随机驗證碼
    public static String getYzm() {
        String s = "";
        Random ran = new Random(System.currentTimeMillis());
        for (int i = 0; i < 4; i++) {
            s = s + ran.nextInt(10);
        }
        return s;
    }

    public static String urlEncoded(String paramString) {
        if (paramString == null || paramString.equals("")) {
            return "";
        }
        try {
            String str = new String(paramString.getBytes(), "UTF-8");
            str = URLEncoder.encode(str, "UTF-8");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String urlDecoded(String paramString) {
        if (paramString == null || paramString.equals("")) {
            return "";
        }
        try {
            String str = new String(paramString.getBytes(), "UTF-8");
            str = URLDecoder.decode(str, "UTF-8");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
